package logic

import (
	"context"
	"product/model/mysql"
	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *productrpc.ListRequest) (*productrpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var products []mysql.Product
	mysql.DB.Debug().Model(&products).Limit(int(in.Size)).Offset(int(offset)).Where("product like ?", "%"+in.Product+"%").Order("status  desc").Find(&products)

	var liststruct []*productrpc.ListStruct

	for _, lists := range products {
		list := &productrpc.ListStruct{
			Product: lists.Product,
			Img:     lists.Img,
			Status:  lists.Status,
		}
		liststruct = append(liststruct, list)
	}

	return &productrpc.ListResponse{List: liststruct}, nil
}
